﻿using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace WindStyle.SPEntity.Converters
{
    public class StringConverter : IValueConverter
    {
        public object ToFieldValue(object value, Type targetType, ConversionContext context)
        {
            var valueType = value.GetType();
            if (valueType.IsEnum)
            {
                var member = valueType.GetField(value.ToString());
                if (member != null)
                {
                    var attributes = member.GetCustomAttributes(typeof(Attributes.EnumMemberAttribute), false);
                    if (attributes.Any())
                        return (attributes.First() as Attributes.EnumMemberAttribute).Name;
                }
            }
            else if (valueType == typeof(Guid))
                return value.ToString();
            return Convert.ChangeType(value, targetType);
        }

        public object ToPropertyValue(object value, Type targetType, ConversionContext context)
        {
            if (targetType.IsEnum)
            {
                var members = targetType.GetFields(BindingFlags.Static | BindingFlags.Public);
                foreach (var member in members)
                {
                    var attributes = member.GetCustomAttributes(typeof(Attributes.EnumMemberAttribute), false);
                    if (attributes.Any()
                        && (attributes.First() as Attributes.EnumMemberAttribute).Name.Equals(value))
                        return Enum.ToObject(targetType, targetType.InvokeMember(member.Name, System.Reflection.BindingFlags.GetField, null, null, null));
                }
            }
            else if (targetType == typeof(Guid))
                return new Guid(value.ToString());

            return Convert.ChangeType(value, targetType);
        }
    }
}
